<?php

/**
 * 夏日葵电商系统
 * http://www.xiarikui.com
 */

namespace App\Controller;

use App\Model\UserModel;
use Think\Cache\Driver\Redis;
use Think\Page;
use Think\Verify;

class UserController extends MobileBaseController {

    public $user_id = 0;
    public $user = array();
    public $userModel;

    /**
     * 初始化操作
     */
    public function _initialize() {
        parent::_initialize();
        $this->userModel = new UserModel();
        if (!in_array(ACTION_NAME, array('reg', 'login', 'loginPlugin', 'getRegionList', 'thirdLogin', 'checkMobileUser', 'sendSmsCode', 'getUserToken'))) {

        }
    }

    public function getUserToken() {
        $user = session('user');
        jsonReturn(1, '查询成功', array('token' => $user['token']));
    }


    /**
     * 赏金统计
     */
    public function bonus_list() {
        if(!$this->user_id){
            jsonReturn(false,'请先登陆');
        }
        $return = array();

        $sign = I('post.sign');
        $page = I('post.page');
        $limit = I('post.limit');

        if($sign == 1) {
            $info = $this->userModel->getInfo($this->user_id);
            if ($info['status'] != 1) {
                jsonReturn(false, $info['msg']);
            }
            $return['bonus'] = $info['result']['bonus_money'];
            $return['reward'] = $info['result']['reward_money'];
            $return['charge'] = $info['result']['charge_money'];
            $return['outcash'] = $info['result']['outcash_money'];
        }

        $count = $this->userModel->getBonusList($page,$limit,1);
        $lists = $this->userModel->getBonusList($page,$limit,0);

        $return['data'] = $lists;
        $return['page'] = $page;
        $return['total'] = $count;

        jsonReturn($return);
    }

    public function bonus_detail() {
        if(!$this->user_id){
            jsonReturn(false,'请先登陆');
        }

        $id = I('post.id');

        $find = $this->userModel->getBonusDetail($id);

        if($find){
            $type= C('ACCOUNTING_LOG_TYPE');

            $arr['merchants'] = $find['shop_sn'];
            $arr['orderno'] = $find['trade_sn'];
            $arr['paytime'] = date('Y-m-d H:i', $find['pay_time']);
            $arr['price'] = $find['money'];
            $arr['title'] = $find['title'];
            $arr['typedetail'] = $type[$find['type']];
        }
        jsonReturn($arr);
    }



    /**
     * 问题统计
     */
    public function question_list() {
        if(!$this->user_id){
            jsonReturn(false,'请先登陆');
        }
        $return = array();

        $info = $this->userModel->getInfo($this->user_id);
        if ($info['status'] != 1) {
            jsonReturn(false, $info['msg']);
        }
        $return['adoption'] = $info['result']['adoption_num'];
        $return['count'] = M('answer')->where('accountant_id = '.$this->user_id)->count();

        $lists = $this->userModel->getQuestionDetail($this->user_id);

        $return['data'] = $lists['data'];
        $return['total'] = $lists['total'];

        jsonReturn($return);
    }



    /**
     * 退出登录
     */
    public function logout() {
        if(!$this->user_id){
            jsonReturn(false,'请先登陆');
        }
        session_unset();
        session_destroy();
        //setcookie('cn', '', time() - 3600, '/');
        //setcookie('user_id', '', time() - 3600, '/');
        M('accountant_users')->where('au_id = '.$this->user_id)->setField('registered_id','');
        jsonReturn(true, '退出成功！');
    }

    /**
     * 账户资金
     */
    public function account() {
        $user = session('user');
        //获取账户资金记录
        $data = $this->userModel->getUserLog($this->user_id, I('post.type'));
        $userLog = $data['result'];

        $this->assign('user', $user);
        $this->assign('userLog', $userLog);
        $this->assign('page', $data['show']);

        if ($_GET['is_ajax']) {
            $this->display('ajax_account_list');
            exit;
        }
        $this->display();
    }

    /**
     * 优惠券
     */
    public function getCoupon() {
        $user_id = $this->user_id;
        $type = I('post.type');
        $data = $this->userModel->getCoupon($user_id, $type);
        jsonReturn(1, '查询成功', $data['result']);
    }

    /**
     *  登录
     */
    public function login() {
        $mobile = I('post.phone_num', '');
        $password = I('post.password');
        $registered_id = I('post.registered_id');
        $data = $this->userModel->appLogin($mobile, $password,$registered_id);
        if($data['status'] == 1){
            jsonReturn($data['result']);
        }
        jsonReturn(false,$data['msg']);
    }

    /**
     *  登录
     */
    public function get_info() {
        if(!$this->user_id){
            jsonReturn(false,'请先登陆');
        }
        $data = $this->userModel->getInfo($this->user_id);

        if($data['status'] == 1){
            jsonReturn($data['result']);
        }
        jsonReturn(false,$data['msg']);
    }

    public function update_info() {

        if(!$this->user_id){
            jsonReturn(false,'请先登陆');
        }
        $post = I('post.');
        if(!$post){
            jsonReturn(false,'请填入信息');
        }

        $data = $this->userModel->updateInfo($this->user_id,$post);
        if($data['status'] == 1){
            jsonReturn(true,$data['msg']);
        }
        jsonReturn(false,$data['msg']);
    }


    public function update_password() {
        if(!$this->user_id){
            jsonReturn(false,'请先登陆');
        }
        $post = I('post.');
        if(!$post){
            jsonReturn(false,'请填入信息');
        }
        $data = $this->userModel->updatePassword($this->user_id,$post);
        if($data['status'] == 1){
            jsonReturn(true,$data['msg']);
        }
        jsonReturn(false,$data['msg']);
    }

    public function get_code() {

        $phone_num = I('post.phone_num');
        $res = $this->userModel->sendSmsCode($phone_num);
        $bool = $res['status'] == 1 ? true : false;

        jsonReturn( $bool , $res['msg']);
    }


    public function verify_num() {

        $phone_num = I('post.phone');
        $identifying_code = I('post.identifying_code');

        $res = $this->userModel->checkSmsCode($phone_num,$identifying_code);
        $bool = $res['status'] == 1 ? true : false;

        jsonReturn( $bool , $res['msg']);
    }

    public function retrievepassword(){
        $post = I('post.');
        if(!$post){
            jsonReturn(false,'请填入信息');
        }
        $data = $this->userModel->retrievePassword($post);
        if($data['status'] == 1){
            jsonReturn(true,$data['msg']);
        }
        jsonReturn(false,$data['msg']);
    }

    /**
     * 第三方登录
     */
    public function thirdLogin() {
        $map['openid'] = I('openid', '');
        $map['unionid'] = I('unionid', '');
        $map['oauth'] = I('from', '');
        $map['nickname'] = I('nickname', 'xiarikui_' . rand(1, 9999));
        $map['head_pic'] = I('head_pic', '');
        $map['is_app'] = 1;
        $res = $this->userModel->thirdLogin($map);
        $this->ajaxReturn($res);
    }

    /**
     *  登录插件
     */
    public function loginPlugin() {
        $loginPlugin = M('Plugin')->where("`type`='login' and status = 1 ")->select();
        if (count($loginPlugin) > 0) {
            jsonReturn(1, '第三方登录', $loginPlugin);
        } else {
            jsonReturn(-1, '无第三方登录');
        }
    }

    /**
     *  注册
     */
    public function reg() {

        $post = I('post.', '');

        $data = $this->userModel->reg($post);
        if($data['status'] == 1){
            jsonReturn(true,$data['msg']);
        }
        jsonReturn(false,$data['msg']);

    }


    /**
     * 上传头像
     */
    public function uploadImg() {
        $savePath = './Public/upload/head_pic/';
        $info = $this->upload($savePath);
        $this->ajaxReturn($info);
    }

    /**
     * 上传评论图片
     */
    public function uploadCommentImg() {
        $savePath = './Public/upload/comment/';
        $info = $this->upload($savePath);
        $this->ajaxReturn($info);
    }

    /**
     * 上传退货商品图片
     */
    public function uploadReturnImg() {
        $savePath = './Public/upload/return_goods/';
        $info = $this->upload($savePath);
        $this->ajaxReturn($info);
    }

    protected function upload($path, $size = 3145728, $exts = ['jpg', 'gif', 'png', 'jpeg']) {
        $upload = new \Think\Upload(); // 实例化上传类
        $upload->maxSize = $size; // 设置附件上传大小
        $upload->exts = $exts; // 设置附件上传类型
        $upload->rootPath = $path; // 设置附件上传根目录
        $upload->autoSub = true;
        $upload->subName = array(
            'date',
            'Ymd'
        );
        // 上传文件
        $info = $upload->upload();
        if (!$info) { // 上传错误提示错误信息
            return array('status' => -1, 'msg' => $upload->getError());
        } else {
            $data = array('urlpath' => $path . $info['head']['savepath'] . $info['head']['savename']);
            return array('status' => 1, 'msg' => '上传成功', 'result' => $data);
        }
    }

    /**
     * 订单列表
     */
    public function getOrderList() {
        $user_id = $this->user_id;
        $type = I('post.type');
        $where = ' user_id=' . $user_id;
        if (strtoupper($type) != "ALL") {
            $where .= C(strtoupper($type));
        }
        $rs = M('order')->where($where)->select();
        $Page = new Page(count($rs), 10);
        $show = $Page->show();
        $order_str = "order_id DESC";
        $orderList = M('order')->where($where)->limit($Page->firstRow . ',' . $Page->listRows)->order($order_str)->select();
        //获取订单商品
        foreach ($orderList as $k => $v) {
            $orderList[$k] = set_btn_order_status($v);  // 添加属性  包括按钮显示属性 和 订单状态显示属性
            //$orderList[$k]['total_fee'] = $v['goods_amount'] + $v['shipping_fee'] - $v['integral_money'] -$v['bonus'] - $v['discount']; //订单总额
            $data = $this->userModel->getOrderGoods($v['order_id']);
            $orderList[$k]['goodsList'] = $data['result'];
        }
        if (count($orderList) > 0) {
            jsonReturn(1, '成功', $orderList);
        } else {
            jsonReturn(1, '无数据');
        }
    }

    /**
     * 订单详情
     */
    public function orderDetail() {
        $order_id = I('post.order_id');
        $user_id = $this->user_id;
        $map['user_id'] = $user_id;
        $map['order_id'] = $order_id;
        $order_info = M('order')->where($map)->find();
        $province = M('region')->where('level=1' . " and id={$order_info['province']}")->getField('name');
        $city = M('region')->where('level=2' . " and id={$order_info['city']}")->getField('name');
        $district = M('region')->where('level=3' . " and id={$order_info['district']}")->getField('name');
        $order_info['province_name'] = $province;
        $order_info['city_name'] = $city;
        $order_info['district_name'] = $district;
        $order_info['pay_date'] = date('Y-m-d', strtotime("+1 day")); //付款期限
        $order_info['invoice_no'] = empty($order_info['invoice_no']) ? '' : $order_info['invoice_no'];

        if (!$order_info) {
            jsonReturn(-1, '无此订单');
        }
        $order_info = set_btn_order_status($order_info);  // 添加属性  包括按钮显示属性 和 订单状态显示属性
        //获取订单商品
        $data = $this->userModel->getOrderGoods($order_info['order_id']);
        $order_info['goodsList'] = $data['result'];
        //$order_info['total_fee'] = $order_info['goods_price'] + $order_info['shipping_price'] - $order_info['integral_money'] -$order_info['coupon_price'] - $order_info['discount'];
//        $region_list = get_region_list();
        $invoice_no = M('Delivery')->where("order_id = $order_id")->getField('invoice_no', true);
        if (!empty($invoice_no)) {
            $order_info['invoice_no'] = implode(' , ', $invoice_no);
        } else {
            $order_info['invoice_no'] = '';
        }
        //获取订单操作记录
//        $orderRemark = M('order_remark')->where(array('order_id' => $order_id))->select();
        $return_data = array(
            'order_info' => $order_info, //订单信息
//            'order_remark' => $orderRemark //订单备注
        );
        jsonReturn(1, '成功', $return_data);
    }

    /**
     * 查看物流
     */
    public function viewExpress() {
        $order_id = I('post.order_id');
        $result = $order_goods = $delivery = array();
        $order_goods = M('order_goods')->alias('as o')->field('o.*,g.original_img')->join(array(' LEFT JOIN xrk_goods AS g ON g.goods_id = o.goods_id'))->where("o.order_id=$order_id")->select();
//        dump($order_goods);die();
        $user_id = $this->user_id;
        $delivery = M('delivery')->where("order_id={$order_id} and user_id={$user_id}")->limit(1)->find();
        $delivery['best_time'] = empty($delivery['best_time']) ? '' : $delivery['best_time'];
        $delivery['tel'] = empty($delivery['tel']) ? '' : $delivery['tel'];
        if ($delivery['shipping_code'] && $delivery['invoice_no']) {
            $result = queryExpress($delivery['shipping_code'], $delivery['invoice_no']);
        }
        $return_data = array(
            'result' => $result,
            'order_goods' => $order_goods,
            'delivery' => $delivery
        );
        jsonReturn(1, '成功', $return_data);
    }

    /**
     * 取消订单
     */
    public function cancelOrder() {
        $order_id = I('post.order_id');
        $user_id = $this->user_id;
        if (!$order_id > 0) {
            jsonReturn(-1, '参数错误');
        }
        $data = $this->userModel->cancelOrder($user_id, $order_id);
        $this->ajaxReturn($data);
    }

    /**
     * 用户地址列表
     */
    public function getAddressList() {
        $user_id = $this->user_id;
        $addressLists = get_user_addr_list($user_id);
        if (count($addressLists) > 0) {
            jsonReturn(1, '成功', $addressLists);
        } else {
            jsonReturn(1, '没数据', array());
        }
    }

    /**
     * 获取用户默认地址
     */
    public function getUserDefaultAddr() {
        $user_id = $this->user_id;
        $address = M('user_addr')->where("user_id = {$user_id} and is_default=1")->find();
        if (!empty($address)) {
            jsonReturn(1, '成功', $address);
        } else {
            jsonReturn(1, '没数据', array());
        }
    }

    /**
     *   获取地区数据
     */
    public function getRegionList() {
        $region_list = get_app_region_list();
        jsonReturn(1, '成功', $region_list);
    }

    /**
     * 添加地址
     */
    public function addAddress() {
        $user_id = $this->user_id;
        $data = $this->userModel->addAddress($user_id, 0, I('post.'));
        $this->ajaxReturn($data);
    }

    /**
     * 地址编辑
     */
    public function editAddress() {
        $address_id = I('address_id', 0);
        if ($address_id == 0) {
            jsonReturn(-1, '参数错误');
        }
        $user_id = $this->user_id;
//        $address = M('user_addr')->where(array('address_id' => $address_id, 'user_id' => $user_id))->find();
        $data = $this->userModel->addAddress($user_id, $address_id, I('post.'));
        $this->ajaxReturn($data);
    }

    /**
     * 获取省份数据
     */
    public function getProvinceList() {
        $rs = M('region')->where(array('parent_id' => 0, 'level' => 1))->select();
        jsonReturn(1, '成功', $rs);
    }

    /**
     * 设置默认收货地址
     */
    public function setDefaultAdrress() {
        $user_id = $this->user_id;
        $address_id = I('post.address_id');
        if (!$address_id > 0) {
            jsonReturn(-1, '参数错误');
        }
        M('user_addr')->where(array('user_id' => $user_id))->save(array('is_default' => 0));
        $row = M('user_addr')->where(array('user_id' => $user_id, 'address_id' => $address_id))->save(array('is_default' => 1));
        if ($row) {
            jsonReturn(1, '设置成功');
        } else {
            jsonReturn(-1, '设置失败');
        }
    }

    /**
     * 地址删除
     */
    public function delAddress() {
        $user_id = $this->user_id;
        $address_id = I('post.address_id');
        if (!$address_id > 0) {
            jsonReturn(-1, '参数错误');
        }
        $row = M('user_addr')->where(array('user_id' => $user_id, 'address_id' => $address_id))->delete();
        $address = M('user_addr')->where("address_id = $address_id")->find();
        // 如果删除的是默认收货地址 则要把第一个地址设置为默认收货地址
        if ($address['is_default'] == 1) {
            $address2 = M('user_addr')->where("user_id = {$user_id}")->find();
            $address2 && M('user_addr')->where("address_id = {$address2['address_id']}")->save(array('is_default' => 1));
        }
        if ($row) {
            jsonReturn(1, '删除成功');
        } else {
            jsonReturn(-1, '删除失败');
        }
    }

    /**
     * 评论
     */
    public function getComment() {
        $user_id = $this->user_id;
        $page = I('post.page', 1);
        $count = I('post.count', 10);

        $result = CommentService::getComment($user_id, 1, $page, $count);
        if (count($result['list']) > 0) {
            $arr = [];
            foreach ($result['list'] as $item => $value) {
                $arr[$item]['comment']['comment_id'] = $value['comment_id'];
                $arr[$item]['comment']['username'] = $value['username'];
                $arr[$item]['comment']['goods_rank'] = $value['goods_rank'];
                $arr[$item]['comment']['add_time'] = $value['add_time'];
                $arr[$item]['comment']['content'] = $value['content'];
                $arr[$item]['comment']['img'] = strlen(unserialize($value['img'])[0]) ? unserialize($value['img']) : [];
                $arr[$item]['goods']['goods_id'] = $value['goods_id'];
                $arr[$item]['goods']['goods_name'] = $value['goods_name'];
                $arr[$item]['goods']['original_img'] = $value['original_img'];
                $arr[$item]['goods']['goods_num'] = $value['goods_num'];
                $arr[$item]['goods']['market_price'] = $value['market_price'];
                $arr[$item]['goods']['goods_price'] = $value['goods_price'];
                $arr[$item]['goods']['cost_price'] = $value['cost_price'];
                $arr[$item]['goods']['member_goods_price'] = $value['member_goods_price'];
                $arr[$item]['goods']['give_integral'] = $value['give_integral'];
                $arr[$item]['goods']['spec_key'] = $value['spec_key'];
                $arr[$item]['goods']['spec_key_name'] = $value['spec_key_name'];
                $arr[$item]['goods']['delivery_id'] = $value['delivery_id'];
                $arr[$item]['order']['order_id'] = $value['order_id'];
                $arr[$item]['order']['order_sn'] = $value['order_sn'];
                $arr[$item]['order']['order_add_time'] = $value['order_add_time'];
            }
            $result['list'] = $arr;
            jsonReturn(1, 'success', $result);
        } else {
            jsonReturn(-1, '暂无数据', []);
        }
    }

    /**
     * 添加评论
     */
    public function addComment() {
        if (IS_POST) {
            $arr = $_POST['aggregate'];
            $order_id = I('order_id');
            $arr = json_decode($arr, true);
            if (!$arr) {
                jsonReturn(-1, '提交的数据为空');
                die();
            }
            $user_info = $this->user;
            foreach ($arr as $item => $value) {
                $add['goods_id'] = $value['goods_id'];
                $add['email'] = $user_info['email'];
                $add['username'] = $user_info['nickname'];
                $add['order_id'] = $order_id;
//                $imgArr = array();
                $strImage = str_replace("./", "/", $value['image']);
                $arrImage = explode(',', $strImage);
//                foreach ($value['image'] as $k => $v) {
//                    if (!empty($v)) {
//                        array_push($imgArr, substr($v, 1));
//                    }
//                }
//                $img = explode(',', $imgArr);
                $add['img'] = serialize($arrImage);
                $add['content'] = $value['content'];
                $add['goods_rank'] = $value['goods_rank'];
                $add['add_time'] = time();
                $add['ip_address'] = getIP();
                $add['user_id'] = $this->user_id;
                //添加评论
                $result = $this->userModel->addComment($add);
            }
            if ($result['status'] === 1) {
                jsonReturn(1, 'success');
            } else {
                jsonReturn(-1, $result['msg']);
            }
        }
    }

    public function showOrderGoods() {
        if (IS_POST) {
            $rec_id = I('rec_id');
            $order_goods = M('order_goods')->where("rec_id = $rec_id")->find();
            $order_goods['original_img'] = goods_thum_images($order_goods['goods_id'], 200, 200);
            if (!$order_goods) {
                jsonReturn(-1, '没有找到相应的商品信息');
            }
            jsonReturn(1, 'success', $order_goods);
        }
    }

    /**
     * 获取个人信息
     */
    public function getUser() {
        $user_id = $this->user_id;
        $user_info = $this->userModel->getInfo($user_id); // 获取用户信息
        return $this->ajaxReturn($user_info);
    }

    /**
     * 设置个人信息
     */
    public function setUser() {
        $post = I('post.');
        $user_id = $this->user_id;
        $post['pay_password'] ? $post['pay_password'] = $post['pay_password'] : false; //支付密码
        $post['nickname'] ? $post['nickname'] = $post['nickname'] : false; //昵称
        $post['qq'] ? $post['qq'] = $post['qq'] : false;  //QQ号码
        $post['head_pic'] ? $post['head_pic'] = $post['head_pic'] : false; //头像地址
        $post['birthday'] ? $post['birthday'] = strtotime($post['birthday']) : false;  // 生日
        $post['province'] ? $post['province'] = $post['province'] : false;  //省份
        $post['city'] ? $post['city'] = $post['city'] : false;  // 城市
        $post['district'] ? $post['district'] = $post['district'] : false;  //地区
//        $post['email'] ? $post['email'] = $post['email'] : false; //邮箱
        $post['mobile'] ? $post['mobile'] = $post['mobile'] : false; //手机
        $email = $post['email'];
        $mobile = $post['mobile'];
        $code = I('post.mobile_code', '');
//        if (!empty($email)) {
//            $c = M('users')->where("email = '{$post['email']}' and user_id != {$user_id}")->count();
//            if ($c > 0) {
//                jsonReturn(-1, '邮箱已被使用');
//            }
//        }
        if (!empty($mobile)) {
            $c = M('users')->where("mobile = '{$post['mobile']}' and user_id != {$user_id}")->count();
            if ($c > 0) {
                jsonReturn(-1, '手机已被使用');
            }
            if (!$code)
                jsonReturn(-1, '请输入验证码');
            $check_code = $this->userModel->smsCodeVerify($mobile, $code, $this->session_id);
            if ($check_code['status'] != 1)
                jsonReturn(-1, $check_code['msg']);
        }
        if (!$this->userModel->updateinfo($user_id, $post))
            jsonReturn(-1, '保存失败');
        jsonReturn(1, '操作成功');
    }

    /**
     * 两个账号绑定
     */
    public function bindUser() {
        $mobile = I('mobile', 0);
        $code = I('post.code', 0);
        if ($mobile == 0 || $code == 0) {
            jsonReturn(-1, '参数错误');
        }
        $res = $this->userModel->checkSmsCode($mobile, $code);
        if ($res['status'] != 1) {
            $this->ajaxReturn($res);
        }
//        $users = D('Users')->where("mobile={$mobile}")->find();
        $user_id = $this->user_id; //第三方登录用户id
        $userInfo = $this->userModel->bindUser($user_id, $mobile); //返回合并后的用户数据
        jsonReturn(1, '绑定成功', $userInfo);
    }

    /**
     * 检测手机用户
     */
    public function checkMobileUser() {
        $mobile = I('mobile', 0);
        if ($mobile == 0) {
            jsonReturn(-1, '参数错误');
        }
        $users = D('Users')->where("mobile={$mobile}")->find();
        if (!empty($users)) {
            jsonReturn(0, '已存在手机用户');
        } else {
            jsonReturn(1, '可以注册');
        }
    }

    /**
     * 邮箱验证
     */
    public function emailValidate() {
        $user_id = $this->user_id;
        $user_info = $this->userModel->getInfo($user_id); // 获取用户信息
        $user_info = $user_info['result'];
        $step = I('post.step', 1);
        //验证是否未绑定过
        if ($user_info['email_validated'] == 0)
            $step = 2;
        //原邮箱验证是否通过
        if ($user_info['email_validated'] == 1 && session('email_step1') == 1)
            $step = 2;
        if ($user_info['email_validated'] == 1 && session('email_step1') != 1)
            $step = 1;
        if (IS_POST) {
            $email = I('post.email');
            $code = I('post.code');
            $info = session('email_code');
            if (!$info)
                $this->error('非法操作');
            if ($info['email'] == $email || $info['code'] == $code) {
                if ($user_info['email_validated'] == 0 || session('email_step1') == 1) {
                    session('email_code', null);
                    session('email_step1', null);
                    if (!$this->userModel->updateEmailMobile($email, $user_id))
                        $this->error('邮箱已存在');
                    $this->success('绑定成功', U('Home/User/index'));
                }else {
                    session('email_code', null);
                    session('email_step1', 1);
                    redirect(U('Home/User/emailValidate', array('step' => 2)));
                }
                exit;
            }
            $this->error('验证码邮箱不匹配');
        }
        $this->assign('step', $step);
        $this->display();
    }

    /**
     * 手机验证
     */
    public function mobileValidate() {
        $user_id = $this->user_id;
        $user_info = $this->userModel->getInfo($user_id); // 获取用户信息
        $user_info = $user_info['result'];
        $step = I('post.step', 1);
        //验证是否未绑定过
        if ($user_info['mobile_validated'] == 0)
            $step = 2;
        //原手机验证是否通过
        if ($user_info['mobile_validated'] == 1 && session('mobile_step1') == 1)
            $step = 2;
        if ($user_info['mobile_validated'] == 1 && session('mobile_step1') != 1)
            $step = 1;
        if (IS_POST) {
            $mobile = I('post.mobile');
            $code = I('post.code');
            $info = session('mobile_code');
            if (!$info)
                $this->error('非法操作');
            if ($info['email'] == $mobile || $info['code'] == $code) {
                if ($user_info['email_validated'] == 0 || session('email_step1') == 1) {
                    session('mobile_code', null);
                    session('mobile_step1', null);
                    if (!$this->userModel->updateEmailMobile($mobile, $user_id, 2))
                        $this->error('手机已存在');
                    $this->success('绑定成功', U('Home/User/index'));
                }else {
                    session('mobile_code', null);
                    session('email_step1', 1);
                    redirect(U('Home/User/mobileValidate', array('step' => 2)));
                }
                exit;
            }
            $this->error('验证码手机不匹配');
        }
        $this->assign('step', $step);
        $this->display();
    }

    /**
     * 加入收藏
     * @param type $goods_id
     */
    public function addCollect() {
        $goods_id = I('post.goods_id');
        if (!$goods_id > 0) {
            jsonReturn(-1, '参数错误');
        }
        $user_id = $this->user_id;
        $goodsMod = new \Home\Model\GoodsModel();
        $result = $goodsMod->collectGoods($user_id, $goods_id);
        $this->ajaxReturn($result);
    }

    /**
     * 我的收藏
     */
    public function collectList() {
        $user_id = $this->user_id;
        $data = $this->userModel->getGoodsCollect($user_id);
        if (count($data['result']) > 0) {
            foreach ($data['result'] as $key => $value) {
                $data['result'][$key]['selected'] = 0;
            }
            jsonReturn(1, '成功', $data['result']);
        } else {
            jsonReturn(1, '无数据');
        }
    }

    /**
     * 取消收藏
     */
    public function cancelCollect() {
        $ids = I('post.ids', 0);
        $user_id = $this->user_id;
        if ($ids == 0) {
            jsonReturn(-1, '参数错误');
        }
        if (M('goods_collect')->where("collect_id in ($ids) and user_id = $user_id")->delete()) {
            $collect_count = M('GoodsCollect')->where("user_id = $user_id")->count();
            jsonReturn(1, '取消收藏成功', array('collect_count' => $collect_count));
        } else {
            jsonReturn(-1, '取消收藏失败');
        }
    }

    /**
     * 我的留言
     */
    public function messageList() {
        $this->verifyHandle('message');
        $data = I('post.');
        $user_id = $this->user_id;
        $data['user_id'] = $user_id;
        $user = session('user');
        $data['user_name'] = $user['nickname'];
        $data['msg_time'] = time();
        if (M('feedback')->add($data)) {
            $this->success("留言成功", U('User/messageList'));
            exit;
        } else {
            $this->error('留言失败', U('User/messageList'));
            exit;
        }
        $msg_type = array(0 => '留言', 1 => '投诉', 2 => '询问', 3 => '售后', 4 => '求购');
        $count = M('feedback')->where("user_id=" . $user_id)->count();
        $Page = new Page($count, 100);
        $Page->rollPage = 2;
        $message = M('feedback')->where("user_id=" . $user_id)->limit($Page->firstRow . ',' . $Page->listRows)->select();
        $showpage = $Page->show();
        header("Content-type:text/html;charset=utf-8");
        $this->assign('page', $showpage);
        $this->assign('message', $message);
        $this->assign('msg_type', $msg_type);
        $this->display();
    }

    /**
     * 积分 
     */
    public function points() {
        $count = I('count', 10);
        $page = I('page', 1);
        $type = I('type', 1); //1为全部 2为充值记录 3为积分
        $user_id = $this->user_id;
        $userLog = [];
        $rechargeLog = [];
        $userDetail = [];
        $userDetail['integral'] = $this->user['pay_points'];
        $userDetail['balance'] = $this->user['user_money'];
        switch ($type) {
            case 1:
                $userLog = M('user_log')->where("user_id=" . $user_id)->select();
                $userLog = convert_arr_key($userLog, 'change_time');
                $rechargeLog = M('recharge')->where('user_id=' . $user_id . ' and pay_status = 1')->select();
                $rechargeLog = convert_arr_key($rechargeLog, 'pay_time');
                break;
            case 2:
                $rechargeLog = M('recharge')->where('user_id=' . $user_id . ' and pay_status = 1')->select();
                $rechargeLog = convert_arr_key($rechargeLog, 'pay_time');
                break;
            case 3:
                $userLog = M('user_log')->where("user_id=" . $user_id)->select();
                $userLog = convert_arr_key($userLog, 'change_time');
                break;
            default:
                $userLog = M('user_log')->where("user_id=" . $user_id)->select();
                $userLog = convert_arr_key($userLog, 'change_time');
                $rechargeLog = M('recharge')->where('user_id=' . $user_id . ' and pay_status = 1')->select();
                $rechargeLog = convert_arr_key($rechargeLog, 'pay_time');
        }

        $record = $userLog + $rechargeLog;

        krsort($record);
        $newRecord = [];
        $key = 0;
        foreach ($record as $item => $value) {
            if (isset($value['log_id'])) {
                $newRecord[$key]['account'] = '余额:' . $value['user_money'];
                $newRecord[$key]['desc'] = $value['desc'];
                $newRecord[$key]['spendDesc'] = '积分:' . $value['pay_points'];
                $newRecord[$key]['time'] = $value['change_time'];
                $key++;
            } else {
                $newRecord[$key]['account'] = $value['order_sn'];
                $newRecord[$key]['desc'] = '平台充值';
                $newRecord[$key]['spendDesc'] = '金额:' . $value['account'];
                $newRecord[$key]['time'] = $value['pay_time'];
                $key++;
            }
        }
        $sliceRecord = array_slice($newRecord, Server::getPaginationOffset($page, $count), $count);
        $result = [
            'userCons' => $userDetail,
            'list' => $sliceRecord,
            'page' => $page,
            'total' => count($record),
            'count' => $count,
            'inNext' => Server::isHasNextPage(count($record), $page, $count)
        ];
        jsonReturn(1, 'success', $result);
    }

    /**
     * 密码修改
     */
    public function password() {
        //检查是否第三方登录用户
        $user_id = $this->user_id;
        $data = $this->userModel->getInfo($user_id);
        $user = $data['result'];
        if ($user['mobile'] == '' && $user['email'] == '')
            $this->error('请先到电脑端绑定手机', U('/Mobile/User/index'));
        if (IS_POST) {
            $data = $this->userModel->password($user_id, I('post.old_password'), I('post.new_password'), I('post.confirm_password')); // 获取用户信息
            if ($data['status'] == -1)
                $this->error($data['msg']);
            $this->success($data['msg']);
            exit;
        }
        $this->display();
    }

    /**
     * 忘记密码
     */
    function forgetPwd() {
        if ($user_id > 0) {
            header("Location: " . U('User/Index'));
        }
        $username = I('username');
        if (IS_POST) {
            if (!empty($username)) {
                $this->verifyHandle('forget');
                $field = 'mobile';
                if (check_email($username)) {
                    $field = 'email';
                }
                $user = M('users')->where("email='$username' or mobile='$username'")->find();
                if ($user) {
                    session('find_password', array('user_id' => $user['user_id'], 'username' => $username,
                        'email' => $user['email'], 'mobile' => $user['mobile'], 'type' => $field));
                    header("Location: " . U('User/findPwd'));
                    exit;
                } else {
                    $this->error("用户名不存在，请检查");
                }
            }
        }
        $this->display();
    }

    /**
     * 找回密码
     */
    function findPwd() {
        if ($user_id > 0) {
            header("Location: " . U('User/Index'));
        }
        $user = session('find_password');
        if (empty($user)) {
            $this->error("请先验证用户名", U('User/forgetPwd'));
        }
        $this->assign('user', $user);
        $this->display();
    }

    /**
     * 设置密码
     */
    public function setPwd() {
        if ($user_id > 0) {
            header("Location: " . U('User/Index'));
        }
        $check = session('validate_code');
        if (empty($check)) {
            header("Location:" . U('User/forgetPwd'));
        } elseif ($check['is_check'] == 0) {
            $this->error('验证码还未验证通过', U('User/forgetPwd'));
        }
        if (IS_POST) {
            $password = I('post.password');
            $password2 = I('post.password2');
            if ($password2 != $password) {
                $this->error('两次密码不一致', U('User/forgetPwd'));
            }
            if ($check['is_check'] == 1) {
                //$user = get_user_info($check['sender'],1);
                $user = M('users')->where("mobile = '{$check['sender']}' or email = '{$check['sender']}'")->find();
                M('users')->where("user_id=" . $user['user_id'])->save(array('password' => encrypt($password)));
                session('validate_code', null);
                //header("Location:".U('User/setPwd',array('is_set'=>1)));
                $this->success('新密码已设置行牢记新密码', U('User/index'));
                exit;
            } else {
                $this->error('验证码还未验证通过', U('User/forgetPwd'));
            }
        }
        $is_set = I('is_set', 0);
        $this->assign('is_set', $is_set);
        $this->display();
    }

    //发送验证码
    public function sendSmsCode() {
        $mobile = I('mobile');
        $res = $this->userModel->sendSmsCode($mobile);
        $this->ajaxReturn($res);
    }

    //检测验证码
    public function checkSmsCode() {
        $code = I('post.code');
        $mobile = I('mobile');
        $res = $this->userModel->checkSmsCode($code, $mobile);
        $this->ajaxReturn($res);
    }

    /**
     * 验证码验证
     * $id 验证码标示
     */
    private function verifyHandle($id) {
        $verify = new Verify();
        if (!$verify->check(I('post.verify_code'), $id ? $id : 'user_login')) {
            $this->error("验证码错误");
        }
    }

    /**
     * 验证码获取
     */
    public function verify() {
        //验证码类型
        $type = I('post.type') ? I('post.type') : 'user_login';
        $config = array(
            'fontSize' => 40,
            'length' => 4,
            'useCurve' => true,
            'useNoise' => false,
        );
        $Verify = new Verify($config);
        $Verify->entry($type);
    }

    /**
     * 收货确认
     */
    public function receiptConfirm() {
        $order_id = I('post.order_id', 0);
        $user_id = $this->user_id;
        if ($order_id == 0) {
            jsonReturn(-1, '参数错误');
        }
        $res = confirm_order($order_id, $user_id);
        $this->ajaxReturn($res);
    }

    /**
     * 申请退货
     */
    public function orderReturn() {
        $user_id = $this->user_id;
        $order_id = I('order_id', 0);
        $order_sn = I('order_sn', 0);
        $goods_id = I('goods_id', 0);
        $spec_key = I('spec_key'); //商品规格key
        if ($order_id == 0 || !is_numeric($order_id)) {
            $this->ajaxReturn(['status' => -1, 'msg' => '订单id参数有误']);
        }
        if ($order_sn == 0) {
            $this->ajaxReturn(['status' => -1, 'msg' => '订单编号参数有误']);
        }
        if ($goods_id == 0 || !is_numeric($order_id)) {
            $this->ajaxReturn(['status' => -1, 'msg' => '商品id参数有误']);
        }
        if (empty($spec_key) || strlen($spec_key) === 0) {
            $this->ajaxReturn(['status' => -1, 'msg' => '规格参数有误']);
        }


        $c = M('order')->where("order_id = $order_id and user_id = {$user_id}")->count();
        if ($c == 0) {
            $this->ajaxReturn(['status' => '-1', 'msg' => '非法操作']);
//            $this->error('非法操作');
            exit;
        }

        $orderReturn = M('order_return')->where("order_id = $order_id and goods_id = $goods_id and spec_key = '$spec_key'")->find();
        if (!empty($orderReturn)) {
            $this->ajaxReturn(['status' => -1, 'msg' => '已经提交过退货申请']);
//            $this->success('已经提交过退货申请!', U('Mobile/User/orderReturnInfo', array('id' => $orderReturn['id'])));
            exit;
        }
        if (IS_POST) {
            $content = I('reason');
            if (empty($content) || strlen($content) === 0) {
                $this->ajaxReturn(['status' => -1, 'msg' => '请填写退换货原因']);
                die();
            }
            $img = I('imgs');
            $strImage = str_replace("./", "/", $img);
            $data['imgs'] = $strImage;
            $data['order_id'] = $order_id;
            $data['order_sn'] = $order_sn;
            $data['goods_id'] = $goods_id;
            $data['addtime'] = time();
            $data['user_id'] = $user_id;
            $data['type'] = I('type', 1); // 服务类型  退货 或者 换货
            $data['reason'] = htmlspecialchars_decode($content); // 问题描述
            $data['spec_key'] = $spec_key; // 商品规格
            M('order_return')->add($data);
            $this->ajaxReturn(['status' => 1, 'msg' => '申请成功,客服第一时间会帮你处理']);
            exit;
        }

        $goods = M('goods')->field('goods_name,goods_sn,original_img')->where("goods_id = $goods_id")->find();
        $result = [
            'goods' => $goods,
            'order_id' => $order_id,
            'order_sn' => $order_sn,
            'goods_id' => $goods_id,
            'spec_key' => $spec_key
        ];
        $this->ajaxReturn(['status' => 1, 'msg' => 'success', 'result' => $result]);
    }

    /**
     * 退换货数据
     */
    public function getReturnList() {
        $user_id = $this->user_id;
        $page = I('page', 1);
        $count = I('count', 10);
        $counts = M('order_return')->where("user_id = {$user_id}")->count();
//        $page = new Page($count, 4);
        $list = M('order_return')->where("user_id = {$user_id}")->order("id desc")->limit(Server::getPaginationOffset($page, $count) . ",$count")->select();
        if (count($list) > 0) {
            $goods_id_arr = get_arr_column($list, 'goods_id');

            $order_id_arr = get_arr_column($list, 'order_id');
            $goodsList = M('goods')->field('goods_id,goods_name,original_img')->where("goods_id in (" . implode(',', $goods_id_arr) . ")")->select();
            $goodsList = convert_arr_key($goodsList, 'goods_id');
            $spec_key_name = M('order_goods')->where("goods_id in (" . implode(',', $goods_id_arr) . ") and order_id in (" . implode(',', $order_id_arr) . ")")->getField('goods_id,spec_key_name');
            foreach ($list as $key => $value) {
                $list[$key]['goods_name'] = $goodsList[$value['goods_id']]['goods_name'];
                $list[$key]['original_img'] = $goodsList[$value['goods_id']]['original_img'];
                $list[$key]['spec_key_name'] = $spec_key_name[$value['goods_id']];
            }
            $result = [
                'list' => $list,
                'page' => $page,
                'total' => $counts,
                'count' => $count,
                'inNext' => Server::isHasNextPage($counts, $page, $count)
            ];
            jsonReturn(1, '成功', $result);
        } else {
            jsonReturn(-1, '无数据');
        }
    }

    /**
     *  退货详情
     */
    public function orderReturnInfo() {
        $id = I('id', 0);
        $orderReturn = M('order_return')->where("id = $id")->find();
        if ($orderReturn['imgs'])
            $orderReturn['imgs'] = explode(',', $orderReturn['imgs']);
        $goods = M('goods')->where("goods_id = {$orderReturn['goods_id']} ")->find();
        $this->assign('goods', $goods);
        $this->assign('orderReturn', $orderReturn);
        $this->display();
    }

    /**
     * 充值 
     */
    public function recharge() {
        $order_id = I('order_id');
        $paymentList = M('Plugin')->where("`type`='payment' and code!='cod' and  status = 1 and  scene in(0,1)")->select();
        //微信浏览器
        if (strstr($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger')) {
            $paymentList = M('Plugin')->where("`type`='payment' and status = 1 and code='weixin'")->select();
        }
        $paymentList = convert_arr_key($paymentList, 'code');

        foreach ($paymentList as $key => $val) {
            $val['config_value'] = unserialize($val['config_value']);
            if ($val['config_value']['is_bank'] == 2) {
                $bankCodeList[$val['code']] = unserialize($val['bank_code']);
            }
        }
        $bank_img = include 'Application/Home/Conf/bank.php'; // 银行对应图片
        $payment = M('Plugin')->where("`type`='payment' and status = 1")->select();
        $this->assign('paymentList', $paymentList);
        $this->assign('bank_img', $bank_img);
        $this->assign('bankCodeList', $bankCodeList);

        if ($order_id > 0) {
            $order = M('recharge')->where("order_id = $order_id")->find();
            $this->assign('order', $order);
        }
        $this->display();
    }

    /**
     * 申请提现记录
     */
    public function cash() {
        if (IS_POST) {
            $this->verifyHandle('cash');
            $data = I('post.');
            $user_id = $this->user_id;
            $data['create_time'] = time();
            $distribut_min = xrkCache('distribut.min'); // 最少提现额度
            if ($data['money'] < $distribut_min) {
                $this->error('每次最少提现额度' . $distribut_min);
                exit;
            }
            if ($data['money'] > $this->user['user_money']) {
                $this->error("你最多可提现{$this->user['user_money']}账户余额.");
                exit;
            }

            if (M('cash')->add($data)) {
                $this->success("已提交申请");
                exit;
            } else {
                $this->error('提交失败,联系客服!');
                exit;
            }
        }
        $where = " user_id = {$user_id}";
        $count = M('cash')->where($where)->count();
        $page = new Page($count, 10);
        $show = $page->show();
        $list = M('cash')->where($where)->limit("{$page->firstRow},{$page->listRows}")->select();
        $this->assign('show', $show);
        $this->assign('list', $list);
        $this->assign('active', 'cash');
        $this->display();
    }

}
